package com.mcb_wxc.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mcb_wxc.http.HttpRequester;
import com.mcb_wxc.http.HttpRespons;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * Created by 小生
 * 2019/1/10 9:22.
 */
@Slf4j
public class GetLocation {
    //腾讯地图key
    //private String MAPKEY = "WVMBZ-36GWU-I5PVS-BTZKA-P3T3S-HLBXZ"; //测试key
    private static String MAPKEY = "AO6BZ-KULKX-S5Y4A-ZTFE5-K7R46-53FG7";

    /**
     * @param addr
     * 查询的经纬度
     * @return
     * @throws IOException
     */
    public static Object[] getCoordinate(String addr) throws IOException {
        String lng = null;//经度
        String lat = null;//纬度
        String address = null;
        try {
            address = java.net.URLEncoder.encode(addr, "UTF-8");
        }catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String key = "WVMBZ-36GWU-I5PVS-BTZKA-P3T3S-HLBXZ";
        String url = String .format("http://api.map.baidu.com/geocoder?address=%s&output=json&key=%s", address, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {
            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStreamReader insr = null;
        BufferedReader br = null;
        try {
            httpsConn = (URLConnection) myURL.openConnection();// 不使用代理
            if (httpsConn != null) {
                insr = new InputStreamReader( httpsConn.getInputStream(), "UTF-8");
                br = new BufferedReader(insr);
                String data = null;
                int count = 1;
                while((data= br.readLine())!=null){
                    if(count==5){
                        lng = (String)data.subSequence(data.indexOf(":")+1, data.indexOf(","));//经度
                        count++;
                    }else if(count==6){
                        lat = data.substring(data.indexOf(":")+1);//纬度
                        count++;
                    }else{
                        count++;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(insr!=null){
                insr.close();
            }
            if(br!=null){
                br.close();
            }
        }
        return new Object[]{lng,lat};
    }

    /**
     * 查询详细地址
     * @param weft 纬线
     * @param arwp 经线
     */
    public static Map<String, Object> getAddressName(String weft, String arwp) {
        Map<String, Object> datamap = null;
        try {
            String url = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + weft + "," + arwp + "&key=" + MAPKEY + "&get_poi=1";
            System.out.println(url);
            HttpRequester http = new HttpRequester();
            HttpRespons respons = http.sendGet(url);
            JSONObject jsonObject = JSON.parseObject(respons.getContent());
            //System.out.print(jsonObject.toString());
            datamap = jsonObject;
        } catch (Exception e) {
            log.error("获取地址错误-------" + e.getMessage());
        }
        return datamap;
    }

    /**
     * 获取城市名称 ：如 常德
     * @param weft 纬线
     * @param arwp 经线
     */
    public static String getCityName(String weft, String arwp){
        Map<String, Object> map = getAddressName(weft,arwp);
        JSONObject jsonObject = JSON.parseObject(map.get("result")+"");
        Map<String, Object>  datamap = jsonObject;
        Map<String, Object>  adInfo = JSON.parseObject(datamap.get("ad_info")+"");
        String cityName = adInfo.get("city")+"";
        cityName = cityName.substring(0,cityName.length()-1);
        return cityName;
    }

    public static void main(String[] args) {
        try {
            //Object[] o = getCoordinate("湖南省常德市临澧县合口镇九里乡双凤村");
            Object[] o = getCoordinate("广东省中山市");
            System.out.println(o[0]);//经度
            System.out.println(o[1]);//纬度

            System.out.println(getCityName("29.720783","111.60207"));


        }catch (Exception e) {
            log.error("***" + e.getMessage());
        }
    }

}
